package com.quick.newsfeed;

import com.quick.bean.*;
import com.quick.global.GlobalConstants;
import com.quick.utilities.DateUtil;
import com.vaadin.demo.dashboard.HomeView;
import com.vaadin.event.MouseEvents;
import com.vaadin.event.ShortcutAction;
import com.vaadin.event.ShortcutListener;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.ThemeResource;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.themes.BaseTheme;
import java.util.List;

public class NewsfeedWraper extends VerticalLayout {

    private Label synopsis;
    private NewsfeedBean nfDetails;
    private List<EventLikeBean> eventLikesList;
    private List<EventCommentsBean> eventCommentsList;
    private VerticalLayout fields;
    private  Embedded likeImage ;
    private  Embedded commentImage;
    private TextField txtNewComment;
    private VerticalLayout verticalForCommentStack;
    private HorizontalLayout likeCommentBtnLayout;
    private String People_who_like_this="People who like this";

    public NewsfeedWraper(final NewsfeedBean nfDetails, HomeView view) {

        this.nfDetails = nfDetails;
        setCaption(nfDetails.getNfDesc());
        setHeight("100%");
        setWidth("99%");
        setMargin(false);
        addStyleName("whiteBg");
//        addStyleName("no-vertical-drag-hints");
//        addStyleName("no-horizontal-drag-hints");
        
        setData(nfDetails);
        HorizontalLayout details = new HorizontalLayout();
        details.setSpacing(true);
        details.setMargin(false);
        details.setSizeFull();
        addComponent(details);
        setComponentAlignment(details,Alignment.MIDDLE_CENTER);
        addLayoutClickListener(view);


        
       
        /* details.addComponent(video);
        details.setExpandRatio(video, 0.5f); */

        fields = new VerticalLayout();
        fields.setWidth("70%");
        fields.setSpacing(true);
        fields.setMargin(true);
        fields.addStyleName("rightAndLeftBorder");
        fields.addStyleName("whiteBg");
        
        details.addComponent(fields);
        details.setExpandRatio(fields, 2);
        details.setComponentAlignment(fields,Alignment.MIDDLE_CENTER);
        Label label;



//        String cap = "<div style='color:#3b5998;display:inline-block;'> <b>" + nfDetails.getNfOwner() + "</b></div>" + "<div style='color:grey;font-size:13px;display:inline-block;'>&nbsp; shared </div> <div style='color:#3b5998;display:inline-block;'>"
//                + nfDetails.getNfDesc() + "</div>";
        
        String cap = "<div style='color:#3b5998;display:inline-block;'> <b>" + nfDetails.getNfOwner() + "</b></div>" + "<div style='color:grey;font-size:13px;display:inline-block;'>&nbsp; shared &nbsp; </div>";
        label = new Label(cap, ContentMode.HTML);
        label.setWidth("100%");
        
        Button nfDescBtn = new Button(nfDetails.getNfDesc());
        nfDescBtn.addStyleName(BaseTheme.BUTTON_LINK);
        nfDescBtn.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                UI.getCurrent().addWindow(new ViewNewsfeedDetailsWindow(nfDetails));
            }
        });
        
        HorizontalLayout nfHeadLineLayout = new HorizontalLayout();
        nfHeadLineLayout.setSpacing(false);
        nfHeadLineLayout.addComponent(label);
        nfHeadLineLayout.addComponent(nfDescBtn);
        
        
        
        
        //label.setStyleName("deepPinkColor");
        //label.setCaption("");
        fields.addComponent(nfHeadLineLayout);

//        label = new Label("<h4><b>"+eventDetails.getEventOwner()+"</b></h4>",ContentMode.HTML);
//        label.setSizeUndefined();
//        label.setCaption("By");
//        fields.addComponent(label);
//        
//        label = new Label("<h4><b>"+eventDetails.getEventDate()+"</b></h4>",ContentMode.HTML);
//        label.setSizeUndefined();
//        label.setCaption("on");
//        fields.addComponent(label);

        synopsis = new Label();
        synopsis.setWidth("100%");
        synopsis.setData(nfDetails.getNfOwner());
        //synopsis.setCaption(GlobalConstants.emptyString);
        updateSynopsis(nfDetails, false);
        fields.addComponent(synopsis);

        
//        String s = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
//                + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> "
//                + "<html xmlns=\"http://www.w3.org/1999/xhtml\" > "
//                + "<head> "
//                + "<title>Youtube link</title> "
//                + "</head> "
//                + "<body style=\"background: #d0ffd0;\"> "
//                + "<div style='height: 5px;'> "
//                + "<script src='http://demo.vaadin.com/xsembed/getEmbedJs' "
//                + "type='text/javascript'></script> "
//                + " </div> "
//                + "<table align=\"center\" border=\"3\" width='100%' height='100%' > "
//                + "<tr valign=\"top\"> "
//                + "<td> "
//                + "<iframe id=\"ytplayer\" type=\"text/html\" width=\"400\" height=\"300\"\n"
//                + "src='"+nfDetails.getNfUrl()+"'\n"
//                + "frameborder=\"0\" allowfullscreen>"
//                + "</td> "
//                + "</tr> "
//                + "</table> "
//                + "</body> "
//                + "</html>";
        
        
        
      /*  Embedded eYoutube2 = new Embedded(null, new ExternalResource(nfDetails.getNfUrl()));
        eYoutube2.setMimeType("application/x-shockwave-flash");
        eYoutube2.setParameter("allowFullScreen", "true");
        eYoutube2.setWidth("420px");
        eYoutube2.setHeight("265px");
        eYoutube2.setType(Embedded.TYPE_BROWSER); */
        
        String videoId=nfDetails.getNfUrl();
        
        if(videoId.indexOf("=")>0)
        {
            videoId=videoId.substring(videoId.lastIndexOf("=")+1);
        }
        else
        {
            videoId=videoId.substring(videoId.lastIndexOf("/")+1);
        }
        //System.out.println("********videoId="+videoId);
        String str="<!DOCTYPE html>\n" +
"<html>\n" +
"  <body>\n" +
"    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->\n" +
"<iframe id=\"player\" type=\"text/html\" width=\"450\" height=\"250\"\n" +
"  src=\"https://www.youtube.com/embed/"+videoId+"?enablejsapi=1&origin=https://example.com\"\n" +
"  frameborder=\"0\"></iframe>"+
"\n" +
"    <script>\n" +
"      // 2. This code loads the IFrame Player API code asynchronously.\n" +
"      var tag = document.createElement('script');\n" +
"\n" +
"      tag.src = \"https://www.youtube.com/iframe_api\";\n" +
"      var firstScriptTag = document.getElementsByTagName('script')[0];\n" +
"      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n" +
"\n" +
"      // 3. This function creates an <iframe> (and YouTube player)\n" +
"      //    after the API code downloads.\n" +
"      var player;\n" +
"      function onYouTubeIframeAPIReady() {\n" +
"        player = new YT.Player('player', {\n" +
"          height: '250',\n" +
"          width: '450',\n" +
"          videoId: '"+videoId+"',\n" +
"          events: {\n" +
"            'onReady': onPlayerReady,\n" +
"            'onStateChange': onPlayerStateChange\n" +
"          }\n" +
"        });\n" +
"      }\n" +
"\n" +
"      // 4. The API will call this function when the video player is ready.\n" +
"      function onPlayerReady(event) {\n" +
"        event.target.playVideo();\n" +
"      }\n" +
"\n" +
"      // 5. The API calls this function when the player's state changes.\n" +
"      //    The function indicates that when playing a video (state=1),\n" +
"      //    the player should play for six seconds and then stop.\n" +
"      var done = false;\n" +
"      function onPlayerStateChange(event) {\n" +
"        if (event.data == YT.PlayerState.PLAYING && !done) {\n" +
"          setTimeout(stopVideo, 6000);\n" +
"          done = true;\n" +
"        }\n" +
"      }\n" +
"      function stopVideo() {\n" +
"        player.stopVideo();\n" +
"      }\n" +
"    </script>\n" +
"  </body>\n" +
"</html>";
        
        Label video = new Label(str, ContentMode.HTML);
        
        fields.addComponent(video);
        //fields.setExpandRatio(cover, 0.5f);
        
        //more.addStyleName("link");
        //fields.addComponent(more);
        /* more.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                updateSynopsis(eventDetails, true);
                event.getButton().setVisible(false);
                
                fetchEventLikesAndComments();
                showLikeAndCommentsForm();
            }
        }); */

        

//        Button ok = new Button("Close");
//        ok.addStyleName("wide");
//        ok.addStyleName("default");
//        ok.addClickListener(new ClickListener() {
//            @Override
//            public void buttonClick(ClickEvent event) {
//                close();
//            }
//        });
//        footer.addComponent(ok);
//        footer.setComponentAlignment(ok, Alignment.TOP_RIGHT);
//        l.addComponent(footer);
    }
    
    private void showLikeAndCommentsForm() {
        likeCommentBtnLayout = new HorizontalLayout();
        likeCommentBtnLayout.setSpacing(true);
        //likeCommentLayout.setMargin(true);
        //likeCommentBtnLayout.addStyleName("backgroundColor");

        //likeCommentBtnLayout.setWidth("60%");
        Button likeBtn = new Button("Like");
        Button commentBtn = new Button("Comment");

        likeBtn.addStyleName(BaseTheme.BUTTON_LINK);
        likeBtn.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                /* sendLike();
                fetchEventLikesAndComments(); */
                               
                if(verticalForCommentStack!=null)
                    fields.removeComponent(verticalForCommentStack);
                fields.removeComponent(likeCommentBtnLayout);
                showLikeAndCommentsForm();
                showFullCommentsStack();
            }
        });
        commentBtn.addStyleName(BaseTheme.BUTTON_LINK);
        commentBtn.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {  
                showFullCommentsStack();
            }
        });
//        likeBtn.addStyleName("link");
//        commentBtn.addStyleName("link");
        likeCommentBtnLayout.addComponent(likeBtn);
        likeCommentBtnLayout.addComponent(commentBtn);
        likeImage =  new Embedded(null,new ThemeResource("./img/like-icon.jpg"));
        likeImage.setHeight("22px");
        likeImage.setWidth("22px");
        likeImage.addClickListener(new com.vaadin.event.MouseEvents.ClickListener() {

            @Override
            public void click(MouseEvents.ClickEvent event) {
                showLikesWindow();
            }
     });
        likeCommentBtnLayout.addComponent(likeImage);
        likeCommentBtnLayout.addComponent(new Label(GlobalConstants.emptyString + eventLikesList.size() ));
        commentImage =  new Embedded(null,new ThemeResource("./img/comments-icon.jpg"));
        commentImage.setHeight("22px");
        commentImage.setWidth("22px");
        likeCommentBtnLayout.addComponent(commentImage);
        likeCommentBtnLayout.addComponent(new Label(GlobalConstants.emptyString + eventCommentsList.size() ));
        Label eventTime=new Label( DateUtil.getTimeIntervalOfTheActivity(nfDetails.getNfDate()));
        eventTime.addStyleName("lightGrayColorAndSmallFont");
        likeCommentBtnLayout.addComponent(eventTime);
        fields.addComponent(likeCommentBtnLayout);
    }
    private void showLikesWindow() {

        VerticalLayout verticalForCommentStack = new VerticalLayout();
        verticalForCommentStack.setMargin(false);
        verticalForCommentStack.setSpacing(true);
        verticalForCommentStack.setWidth("100%");
        verticalForCommentStack.addStyleName("backgroundColor");
        HorizontalLayout likeNamesLayout;
        for (EventLikeBean like : eventLikesList) {
            likeNamesLayout = new HorizontalLayout();
            likeNamesLayout.addStyleName("whiteBottomBorder");
            likeNamesLayout.setMargin(false);
            likeNamesLayout.setSpacing(false);
            likeNamesLayout.setWidth("100%");
            likeNamesLayout.setHeight("100%");
            Image userImage = new Image(null, new ThemeResource("img/profile-pic.png"));

            userImage.setWidth("30px");
            userImage.setWidth("30px");
            likeNamesLayout.addComponent(userImage);
            likeNamesLayout.setExpandRatio(userImage, 0.5f);
            likeNamesLayout.setComponentAlignment(userImage, Alignment.TOP_LEFT);
            Label lblComment = new Label("<b>" + like.getName() + "</b>", ContentMode.HTML);
            likeNamesLayout.addComponent(lblComment);
            likeNamesLayout.setExpandRatio(lblComment, 1);
            likeNamesLayout.setComponentAlignment(lblComment, Alignment.MIDDLE_LEFT);

            Label lblCommentTime = new Label(DateUtil.getTimeIntervalOfTheActivity(like.getLikeTime()));
            lblCommentTime.addStyleName("lightGrayColorAndSmallFont");
            likeNamesLayout.addComponent(lblCommentTime);
            likeNamesLayout.setExpandRatio(lblCommentTime, 1);
            likeNamesLayout.setComponentAlignment(lblCommentTime, Alignment.MIDDLE_RIGHT);

            verticalForCommentStack.addComponent(likeNamesLayout);

        }

        Window w = new Window(People_who_like_this);
        w.center();
        w.setWidth("35%");
        w.setHeight("40%");
        w.setContent(verticalForCommentStack);
        getUI().getCurrent().addWindow(w);
    }
    private void showFullCommentsStack() 
    {
        if(verticalForCommentStack!=null)
                    fields.removeComponent(verticalForCommentStack);
        
        verticalForCommentStack = new VerticalLayout();
        verticalForCommentStack.setMargin(false);
        verticalForCommentStack.setSpacing(true);
        verticalForCommentStack.setWidth("65%");
        //verticalForCommentStack.setHeight("200px");
        verticalForCommentStack.addStyleName("backgroundColor");
        HorizontalLayout fullCommentsLayout;
        for (EventCommentsBean comment : eventCommentsList) {
            fullCommentsLayout = new HorizontalLayout();
            fullCommentsLayout.addStyleName("whiteBottomBorder");
            fullCommentsLayout.setMargin(false);
            fullCommentsLayout.setSpacing(false);
            fullCommentsLayout.setWidth("100%");
            fullCommentsLayout.setHeight("100%");
            Image userImage = new Image(null, new ThemeResource("img/profile-pic.png"));

            userImage.setWidth("30px");
            userImage.setWidth("30px");
            fullCommentsLayout.addComponent(userImage);
            fullCommentsLayout.setExpandRatio(userImage, 0.5f);
            fullCommentsLayout.setComponentAlignment(userImage, Alignment.TOP_LEFT);
            Label lblComment = new Label("<b>" + comment.getName() + ": </b>" + comment.getCommentBody(), ContentMode.HTML);
            fullCommentsLayout.addComponent(lblComment);
            fullCommentsLayout.setExpandRatio(lblComment, 4);
            fullCommentsLayout.setComponentAlignment(lblComment, Alignment.MIDDLE_LEFT);
            
            Label lblCommentTime=new Label(DateUtil.getTimeIntervalOfTheActivity(comment.getCommentTime()));
            lblCommentTime.addStyleName("lightGrayColorAndSmallFont");
            fullCommentsLayout.addComponent(lblCommentTime);
            fullCommentsLayout.setExpandRatio(lblCommentTime, 1);
            fullCommentsLayout.setComponentAlignment(lblCommentTime, Alignment.MIDDLE_RIGHT);

            verticalForCommentStack.addComponent(fullCommentsLayout);

        }
        fullCommentsLayout = new HorizontalLayout();
        fullCommentsLayout.addStyleName("whiteBottomBorder");
        fullCommentsLayout.setMargin(false);
        fullCommentsLayout.setSpacing(false);
        fullCommentsLayout.setWidth("100%");
        fullCommentsLayout.setHeight("100%");

        Image userImage = new Image(null, new ThemeResource("img/profile-pic.png"));
        userImage.setWidth("30px");
        userImage.setWidth("30px");
        txtNewComment = new TextField();
        txtNewComment.setWidth("100%");
        txtNewComment.setImmediate(true);
        txtNewComment.setInputPrompt("Write a comment...");
        txtNewComment.addShortcutListener(new ShortcutListener("Shortcut Name", ShortcutAction.KeyCode.ENTER, null) {

            @Override
            public void handleAction(Object sender, Object target) {
                if (txtNewComment.getValue() != null && !txtNewComment.getValue().equals(GlobalConstants.emptyString)) {
                    if(txtNewComment.getValue().length()>1000)
                    {
                        Notification.show("Comment cannot be more than 1000 characters.", Notification.Type.WARNING_MESSAGE);
                    }
                    else
                    {
                        /* saveComment(txtNewComment.getValue());
                        fetchEventLikesAndComments(); */
                        fields.removeComponent(verticalForCommentStack);
                        fields.removeComponent(likeCommentBtnLayout);
                        showLikeAndCommentsForm();
                        showFullCommentsStack();
                    }
                }
            }
        });

        fullCommentsLayout.addComponent(userImage);
        fullCommentsLayout.setExpandRatio(userImage, 0.5f);
        fullCommentsLayout.setComponentAlignment(userImage, Alignment.TOP_LEFT);
        fullCommentsLayout.addComponent(txtNewComment);
        fullCommentsLayout.setExpandRatio(txtNewComment, 4);
        fullCommentsLayout.setComponentAlignment(txtNewComment, Alignment.MIDDLE_LEFT);
        verticalForCommentStack.addComponent(fullCommentsLayout);
        fields.addComponent(verticalForCommentStack);
    }
    
    public void updateSynopsis(NewsfeedBean eventDetails, boolean expand) {
        String synopsisText = synopsis.getData().toString();
        if (eventDetails.getNfBody() != null) {
            synopsisText = eventDetails.getNfBody();
            synopsis.setData(eventDetails.getNfBody());
        }
        if (!expand) {
            synopsisText = synopsisText.length() > 200 ? synopsisText.substring(0, 200) + GlobalConstants.tripple_dots : synopsisText;

        }
        synopsis.setValue(synopsisText);
    }
    
    
 /*   private void saveComment(String value) 
    {
          try {
            Userprofile profile = ((Userprofile) getSession().getAttribute(GlobalConstants.CurrentUserProfile));
            JSONObject input = new JSONObject();
            input.put("event_id", nfDetails.getEventDetailId());
            input.put("event_desc", nfDetails.getEventDesc());
            input.put("username", profile.getUsername());
            input.put("name", profile.getName());
            input.put("comment", value);

            Client client = Client.create();
            WebResource webResource = client.resource(GlobalConstants.getProperty(GlobalConstants.SAVE_EVENT_COMMENT));
            ClientResponse response = webResource.type(GlobalConstants.application_json).post(ClientResponse.class, input);

            

            String output = response.getEntity(String.class);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
          
   }

    

    private void sendLike() {
        try {
            Userprofile profile = ((Userprofile) getSession().getAttribute(GlobalConstants.CurrentUserProfile));
            JSONObject input = new JSONObject();
            input.put("event_id", nfDetails.getNfId());
            input.put("username", profile.getUsername());
            input.put("name", profile.getName());

            Client client = Client.create();
            WebResource webResource = client.resource(GlobalConstants.getProperty(GlobalConstants.SAVE_EVENT_LIKE));
            ClientResponse response = webResource.type(GlobalConstants.application_json).post(ClientResponse.class, input);

           

            String output = response.getEntity(String.class);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }

    }
    
        private void fetchEventLikesAndComments() {
        try {
            JSONObject input = new JSONObject();
            input.put("event_id", nfDetails.getNfId());

            Client client = Client.create();
            WebResource webResource = client.resource(GlobalConstants.getProperty(GlobalConstants.FETCH_EVENT_LIKES_BY_ID));
            ClientResponse response = webResource.type(GlobalConstants.application_json).post(ClientResponse.class, input);

          

            JSONObject outNObject = null;
            String output = response.getEntity(String.class);
            outNObject = new JSONObject(output);

             Type listType1 = new TypeToken<ArrayList<EventLikeBean>>() {
            }.getType();
            
             Gson eventLikesGson = new GsonBuilder().setDateFormat(GlobalConstants.gsonTimeFormat).create();       
            eventLikesList = eventLikesGson.fromJson(outNObject.getString(GlobalConstants.eventLikes), listType1);
            
            Type listType2 = new TypeToken<ArrayList<EventCommentsBean>>() {
            }.getType();
            
             Gson eventCommentsGson = new GsonBuilder().setDateFormat(GlobalConstants.gsonTimeFormat).create();       
            eventCommentsList = eventCommentsGson.fromJson(outNObject.getString(GlobalConstants.eventComments), listType2);
            
            System.out.println("eve"+eventLikesList);
            
        } catch (JSONException ex) {
            ex.printStackTrace();
        }

    } */
}